package org.mango.jiayin.operater.operater.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mango.jiayin.operater.operater.Operater;

/**
 * <p>
 * Title: regexReplace
 * </p>
 * <p>
 * Description: 正则替换算子 例如: regexReplace('.*hello.*', 'happy', key)-->判断data中的key是否有'hello'字段,有就替换为'happy'
 * </p>
 *
 * @author ji'anyuan
 * @date 2018年3月10日
 */
public class RegexReplaceOp implements Operater {

  @Override
  public String getName() {
    return "regexReplace";
  }

  @Override
  public Object calc(String[] opParames, Object data, Map<String, Object> nestValues) {
    Operater.checkParames(opParames, 3);

    Object[] values = Operater.getopParamesValues(opParames, data, nestValues);

    if (values[0] instanceof String && values[1] instanceof String && values[2] instanceof String) {
      Pattern p = Pattern.compile((String) values[0]);
      Matcher m = p.matcher((String) values[2]);
      return m.replaceAll((String)values[1]);
    }

    if (values[0] instanceof String && values[1] instanceof String && values[2] instanceof Object[]) {
      Pattern p = Pattern.compile((String) values[0]);
      Object[] arr = (Object[])values[2];
      Object[] copy = new Object[arr.length];
      for(int i=0;i<arr.length;i++){
        Matcher m = p.matcher((String)arr[i]);
        copy[i] = m.replaceAll((String)values[1]);
      }
      return copy;
    }

    if (values[0] instanceof String && values[1] instanceof String && values[2] instanceof List) {
      Pattern p = Pattern.compile((String) values[0]);
      List list = (List)values[2];
      List copy = new ArrayList();
      for(int i=0;i<list.size();i++){
        Matcher m = p.matcher((String)list.get(i));
        copy.set(i,m.replaceAll((String)values[1]));
      }
      return list;
    }

    return null;
  }
}
